# --*-- coding: UTF-8 --*--
from . import *

sys.path.append('..')

root = os.path.dirname(__file__).rsplit('common')[0]

ini_path = '{}/program/conf.ini'.format(root)

xml_path = '{}/AppSettings.xml'.format(root)


# RedisUtil提供静态方法返回redis连接
class RedisUtil:
    @staticmethod
    def get_conn():
        redis_conn = getattr(g, 'redis_conn', None)
        try:
            if redis_conn is None:
                ip = get_xml_value('RedisHost')
                port = get_xml_value('RedisPort')
                redis_conn = g.redis_conn = redis.Redis(
                    host=ip, port=port, db=15,
                    encoding='utf8', charset='utf-8',
                    encoding_errors='ignore',
                    decode_responses=True)
            return redis_conn
        except Exception as e:
            print(e)
            return None


def config(title, key):
    return get_xml_value('filePath')


# 设置值
def set_config(title, key, value, flag=False):
    conf = configparser.ConfigParser()
    try:
        conf.read(ini_path)
        if flag:
            conf.add_section(title)
        conf.set(title, key, value=value)
        conf.write(open(ini_path, 'w'))
    except Exception as e:
        print(e)
    finally:
        conf.clear()


# 格式时间
def time_format(_datetime, _format='%Y-%m-%d'):
    if not _datetime:
        return ''
    else:
        return _datetime.strftime(_format)


# 设置默认值
def str_replace(_str, d=''):
    if _str is None:
        return d
    else:
        return str(_str)


# 获取值
def get_xml_value(key):
    _root = e.parse(xml_path).getroot()
    return _root.find(key).text
